<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Custom Interpolator</title>
    <link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
    <script type="text/javascript" src="../../lib/d3.js"></script>
</head>

<body>

<div id="dollar" class="clear">
    <span>Custom Dollar Interpolation<br></span>
</div>
<div id="alphabet" class="clear">
    <span>Custom Alphabet Interpolation<br></span>
</div>

<script type="text/javascript">
    // dollar custom interpolator example from https://github.com/mbostock/d3/wiki/Transitions#wiki-d3_interpolators
    d3.interpolators.push(function(a, b) { // <-A
      var re = /^\$([0-9,.]+)$/, // <-B
        ma, mb, f = d3.format(",.02f"); 
      if ((ma = re.exec(a)) && (mb = re.exec(b))) { // <-C
        a = parseFloat(ma[1]);
        b = parseFloat(mb[1]) - a;  // <-D
        return function(t) {  // <-E
          return "$" + f(a + b * t); // <-F
        };
      }
    });

    d3.interpolators.push(function(a, b) { // <-G
      var re = /^([a-z])$/, ma, mb; // <-H
      if ((ma = re.exec(a)) && (mb = re.exec(b))) { // <-I
        a = a.charCodeAt(0);
        var delta = a - b.charCodeAt(0); // <-J
        return function(t) { // <-K
          return String.fromCharCode(Math.ceil(a - delta * t));
        };
      }
    });

    var dollarScale = d3.scale.linear()
            .domain([0, 13])
            .range(["$0", "$300"]); // <-L
            
    var alphabetScale = d3.scale.linear()
            .domain([0, 27])
            .range(["a", "z"]); // <-M
        
    function render(scale, selector) {        
        var data = [];
        var max = scale.domain()[1];
        
        for (var i = 0; i < max; ++i) data.push(i);      
        
        d3.select(selector).selectAll("div.cell")
                    .data(data)
                .enter()
                    .append("div")
                        .classed("cell", true)
                    .append("span");

        d3.select(selector).selectAll("div.cell")
                    .data(data)
                .exit().remove();

        d3.select(selector).selectAll("div.cell")
                .data(data)
                .style("display", "inline-block")
                .select("span")
                    .text(function(d,i){return scale(d);}); // <-N
    }

    render(dollarScale, "#dollar");
    render(alphabetScale, "#alphabet");
</script>

</body>

</html>